package ch.ffhs.bscinf2009.organizeanything.gui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import ch.ffhs.bscinf2009.organizeanything.R;

/**
 * @author lir
 * Populates a screen where the user can set the possible values of a ChooserType
 */
public class CreateDefinitionChooser extends Activity {
	private TableLayout tb;
	private String values = "";
	private int spinnerID = -1;
	private TextView propertyName;
	private String propertyTitle;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_definition_chooser);
		tb = (TableLayout) findViewById(R.id.table_manage_object);
		spinnerID = getIntent().getExtras().getInt("spinnerID", -2);
		propertyTitle = getIntent().getExtras().getString("propertyName");
		propertyName = (TextView) findViewById(R.id.manage_property_name);
		propertyName.setText(propertyTitle);
		addValue(new View(this));
		addValue(null);
	}
	
	@Override
	public void onBackPressed() {
		//catch the back button to not loose the information typed
	}
	
	/**
	 * adds a new value field
	 * @param view the view the method was called from
	 */
	public void addValue(View view){
		TableRow tr = new TableRow(getBaseContext());
		EditText etValue = new EditText(this);
		etValue.setText("");
		if(view!=null){
			etValue.requestFocus();
		}
		tr.addView(etValue);
		tb.addView(tr);	
	}
	
	/**
	 * removes the last value field
	 * @param view the view the method was called from
	 */
	public void removeValue(View view){
		int i = tb.getChildCount();
		if (i > 3) {
			TableRow tr = (TableRow) tb.getChildAt(i-1);
			tb.removeView(tr);
		}
	}
	
	/**
	 * Stores the values in the activity result so it can be used from the calling activity
	 * @param view the view the method was called from
	 */
	public void saveValues(View view){
		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		//i starts at 1, because 0 is the table header which is not needed data
		for(int i=1; i < tb.getChildCount(); i++){
			TableRow tr = (TableRow) tb.getChildAt(i);
			EditText etValue = (EditText) tr.getChildAt(0);
			if(i < tb.getChildCount() -1){
				values += etValue.getText().toString() + ";";
			} else{
				values += etValue.getText().toString();
			}
			
		}
		bundle.putString("VALUES", values);
		bundle.putInt("spinnerID", spinnerID);
		intent.putExtras(bundle);
		setResult(1, intent);
		finish();
	}
}
